package imdbfolder.gui;

import imdbfolder.app.Application;
import imdbfolder.data.Movie;
import imdbfolder.data.MovieSelectionMap;
import imdbfolder.workers.MovieInfoFetcher;

import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.ExecutionException;


public class MovieController {

    private MoviePanel view;

    public MoviePanel getView() {
        return view;
    }

    private Movie movie;

    private final MovieListController listController;

    public Movie getMovie() {
        return movie;
    }

    public MovieController(MovieListController listController, Movie movie) {
        this.listController = listController;
        this.movie = movie;

        view = new MoviePanel(this);
    }

    public void updateIfNecessary() {
        if (!movie.isFetchedInfo()) {
            updateMovieInfo();
        }
    }

    protected void saveMovie() {
        MovieSelectionMap.getInstance().putMovie(movie);
    }

    public void openMovie() {
        try {
            Desktop.getDesktop().open(new File(movie.getFileName()));
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void updateMovieInfo() {
        view.setUpdating();

        //System.out.println("Start fetcher");

        Application.runTask(new MovieInfoFetcher(movie) {
            @Override
            public void onDone() {
                try {
                    movie = get();

                    saveMovie();

                    view.initialize();
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
                catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
        }, true);
    }

    public void clearMovieInfo() {
        MovieSelectionMap.getInstance().clearMovie(movie);

        listController.clearKnownMovie(movie, view);
    }

    public void setVisible(boolean state) {
        view.setVisible(state);
    }
}
